<!-- 费用科目 -->
<template>
  <div class="expense">
    <!-- 受试者 -->
    <s-table
      v-if="$auth('PROJECT.PROJECT_EXPENSE_PATIENT') || $auth('PROJECT.PROJECT_EXPENSE_RESEARCHER')"
      ref="table"
      rowKey="id"
      :columns="columns"
      bordered
      :loading="loading"
      :data="loadData">
      <!-- 表头 start -->
      <template slot="title">
        <div style="display: flex; justify-content: space-between">
          <div>
            <a-radio-group v-model="queryParam.type" default-value="1" button-style="solid" @change="handleRadio()">
              <a-radio-button :value="1" v-if="$auth('PROJECT.PROJECT_EXPENSE_RESEARCHER')"> 研究者 </a-radio-button>
              <a-radio-button :value="2" v-if="$auth('PROJECT.PROJECT_EXPENSE_PATIENT')"> 受试者 </a-radio-button>
            </a-radio-group>
          </div>
          <div style="display: flex;">
            <a-button type="primary" icon="plus" @click="activeAdd()" v-if="(queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_ADD')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_ADD') )">新增</a-button>
            <a-button v-if="(queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_ADD')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_ADD') )" :href="$const.TEMPLATE_PATH.EXPENSE | dealImageUrl" icon="download" style="margin:0 20px">模板下载</a-button>
            <a-upload
              v-if="(queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_ADD')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_ADD') )"
              ref="import"
              accept=".xlsx"
              name="file"
              list-type="picture"
              :before-upload="beforeUploadSite"
              :preview-file="clickImport"
            >
              <a-button type="dashed"><a-icon type="upload" />导入</a-button>
            </a-upload>
            <a-button style="margin-left: 20px" type="button" icon="download" v-if="(queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_EXPORT')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_EXPORT') )" @click="clickExport">导出</a-button>
          </div>
        </div>
      </template>
      <!-- 是否默认 -->
      <template slot="id" slot-scope="text, record, index">
        {{ index | getPageIndex($refs.table) }}
      </template>
      <!-- <span slot="defaulted" slot-scope="text, record">
        {{ record.defaulted | enumValueByKey($const.IS_DEFAULT) }}
      </span> -->
      <span slot="status" slot-scope="text, record">
        <!-- {{ record.status }} -->
        {{ record.status | enumValueByKey($const.EXPENSE__CURRENT_STATUS) }}
      </span>
      <span slot="amt" slot-scope="text, record">
        <span v-if="record.amt === 0">非默认</span>
        <span v-else>{{ record.amt | formatAmount }}</span>
      </span>
      <!-- 审批资料默认 -->
      <span slot="apv" slot-scope="text, record">
        {{ record.apv | enumValueByKey($const.APPROVAL_FILE) }}
      </span>
      <!-- 是否默认 end-->

      <!-- 操作区 start -->
      <template slot="operation" slot-scope="text, record">
        <a @click="activeEdit(record)" v-if="(queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_EDIT')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_EDIT') )">编辑</a>
        <a-divider type="vertical" />
        <a v-if="record.status !== 1 && ((queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_STATUS')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_STATUS')) )" @click="switchStatus(record, 1)">启用</a>
        <a @click="switchStatus(record, 0)" v-if="record.status === 1 && ( (queryParam.type == 1 && $auth('PROJECT.PROJECT_EXPENSE_STATUS')) || (queryParam.type == 2 && $auth('PROJECT.PROJECT_EXPENSE_PATIENT_STATUS')) )">禁用</a>
      </template>
      <!-- 操作区 end -->
    </s-table>
    <!-- 新增弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="onSubmit"
      @cancel="handleCancel"
    >
      <!-- 新增表单 start -->
      <!-- !isAdd 在新增状态 不需要填写的-->
      <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="申请类目" prop="applyType">
          <a-input v-if="isAdd" v-model="form.applyType" placeholder="请输入类目名词" />
          <span v-else>{{ form.applyType }}</span>
        </a-form-model-item>
        <a-form-model-item label="适用类型">
          <span>{{ queryParam.type === 1 ? '研究者费用' : '受试者费用' }}</span>
        </a-form-model-item>
        <a-form-model-item label="默认金额" prop="amt">
          <div>
            <a-switch v-model="form.defaulted" @change="handleDefaultChange" />
            <a-input
              :min="0"
              :max="1000000000"
              v-model="form.amt"
              placeholder="请输入默认金额，默认金额为0"
              style="width: 100%"
              :disabled="!form.defaulted"
              @input="(e) => (this.form.amt = $commonMethods.moneyCheck(e.target.value))"
            />
          </div>
        </a-form-model-item>
        <a-form-model-item label="审批资料">
          <a-switch v-model="form.apv" />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-input v-model="form.remark" type="textarea" placeholder="备注" />
        </a-form-model-item>
      </a-form-model>
      <!-- 新增表单 end -->
    </a-modal>
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import overview from '@/monitor/views/overview/detail/responsible/components/expense/expense'
import { getList, updata, add, toggleStatus, expenseImport, expenseExport } from '@/api/overview/cost'
import { exportExcel } from '@/utils/util'
import clonedeep from 'lodash.clonedeep'
import { buildPaginationObj } from '@/components/Table'

const watch = monitor(overview)
const columnsPM = [
  {
    title: '序号',
    dataIndex: 'id',
    scopedSlots: { customRender: 'id' }
  },
  {
    title: '申请类目',
    dataIndex: 'applyType'
  },
  // {
  //   title: '是否默认',
  //   dataIndex: 'defaulted',
  //   scopedSlots: { customRender: 'defaulted' }
  // },
  {
    title: '默认金额',
    dataIndex: 'amt',
    scopedSlots: { customRender: 'amt' }
  },
  {
    title: '审批资料',
    dataIndex: 'apv',
    scopedSlots: { customRender: 'apv' }
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsOthers = [
  {
    title: '序号',
    dataIndex: 'id'
  },
  {
    title: '申请类目',
    dataIndex: 'applyType'
  },
  // {
  //   title: '是否默认',
  //   dataIndex: 'defaulted',
  //   scopedSlots: { customRender: 'defaulted' }
  // },
  {
    title: '默认金额',
    dataIndex: 'amt'
  },
  {
    title: '审批资料',
    dataIndex: 'apv',
    scopedSlots: { customRender: 'apv' }
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  }
]

export default {
  name: '',
  data () {
    return {
      columns: (this.$auth('PROJECT.PROJECT_EXPENSE_EDIT') || this.$auth('PROJECT.PROJECT_EXPENSE_STATUS')) ? columnsPM : columnsOthers,
      modalTitle: '',
      queryParam: {
        type: 1, // 1：研究者   2：受试者
        proId: this.$route.query.id // 项目Id
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      tableData: [], // 表单数据
      form: {
        // 新增表单
        applyType: null,
        type: null
      },
      isAdd: false,
      visible: false, // 新增弹框标识
      confirmLoading: false,
      loading: false,
      loadData: parameter => {
        if ((this.queryParam.type === 1 && this.$auth('PROJECT.PROJECT_EXPENSE_RESEARCHER')) ||
        (this.queryParam.type === 2 && this.$auth('PROJECT.PROJECT_EXPENSE_PATIENT'))) {
          return getList(Object.assign(parameter, this.queryParam)).then(res => {
          return res
        })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      rules: {
        // 校验规则
        applyType: [
          { required: true, message: '请输入类目', trigger: 'change' },
          { min: 1, max: 32, message: '类目不能超过32位', trigger: 'change' }
        ],
        amt: [
          { required: false, trigger: 'change' },
          { pattern: /^\d{1,8}(\.\d{0,2}$)?/, message: '数字不能超过10位，小数点后不能超过两位' }
        ]
      }
    }
  },
  created () {
    console.log(this.$commonMethods)
    if (this.$auth('PROJECT.PROJECT_EXPENSE_RESEARCHER')) this.queryParam.type = 1
    else if (this.$auth('PROJECT.PROJECT_EXPENSE_PATIENT')) this.queryParam.type = 2
  },
  methods: watch({
    // 受试人列表
    getList (params = {}) {
      this.loading = true
      getList({ ...this.page, ...params })
        .then(res => {
          this.tableData = res.content
          this.pagination.total = res.totalCount
          this.pagination.current = res.pageNumber
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 开始新增
    activeAdd () {
      // 清空上次编辑状态
      this.visible = true
      this.form = { type: null }
      this.modalTitle = '新增'
      this.isAdd = true
      this.form.type = this.queryParam.type
    },
    // 开始编辑
    activeEdit (record) {
      const obj = record
      delete obj.createTime // 去除掉多余字段
      delete obj.modifyTime
      this.form = {}
      this.modalTitle = '编辑'
      this.isAdd = false
      this.visible = true
      this.form = { ...record, defaulted: !!record.defaulted, apv: !!record.apv }
    },
    // 翻页事件
    changePage (page, pageSize) {
      this.page.pageNumber = page
      this.page.pageSize = pageSize
      this.getList()
    },
    // 切换人员回调
    handleRadio () {
      this.loadData(this.queryParam)
      this.$refs.table.refresh(true)
    },
    // 新增提交
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const form = clonedeep(this.form)
          // switch未找到替换值的选项，这里手动处理一下。以后可以优化
          form.defaulted = form.defaulted ? 1 : 0
          form.apv = form.apv ? 1 : 0
          const num = form.amt ? Number(form.amt) : 0
          form.amt = num.toFixed(2)
          if (this.isAdd) {
            // 新增
            form.proId = this.$route.query.id // 新增状态多传一个proId
            add(form).then(res => {
              this.$message.success('操作成功！')
              this.confirmLoading = false
              this.$refs.table.refresh(true)
              this.visible = false
            }).catch(_ => {
              this.confirmLoading = false
            })
          } else {
            // 编辑
            if (this.queryParam.type === 1) {
              this.editResearch()
            } else {
              this.editSubject()
            }
            updata(form).then(res => {
              this.$message.success('操作成功！')
              this.confirmLoading = false
              this.$refs.table.refresh(true)
              this.visible = false
            }).catch(_ => {
              this.confirmLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 启用禁用操作
    switchStatus (record, status) {
      // 编辑
      toggleStatus({
        id: record.id,
        status
      }).then(res => {
        this.$message.success('操作成功！')
        this.$refs.table.refresh(true)
      })
    },
    // 取消操作
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
    },
    // 表单刷新
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    beforeUploadSite (file) {
      return false
    },
    // 点击导入
    clickImport (file) {
      const params = new FormData()
      params.append('file', file)
      params.append('proId', this.$route.query.id)
      params.append('type', this.queryParam.type)
      return expenseImport(params).then(res => {
        this.$notification.success({
          message: file.name,
          description: '上传成功'
        })
      }).finally(() => {
        this.$refs.import.sFileList = []
        this.$refs.table.refresh(true)
      })
    },
    // 点击导出
    clickExport () {
      // const exportParams = this.queryParam
      // const exportParams = this.$route.query.id
      // exportParams.pageSize = this.pageSize
      const exportParams = { proId: this.$route.query.id, type: this.queryParam.type }
      expenseExport(exportParams).then(res => {
        exportExcel('费用科目', res)
      })
    },
    // 新增科目埋点
    addExpense () {},
    // 编辑科目埋点
    editExpense () {},
    // 研究者科目修改埋点
    editResearch () {},
    // 受试者科目修改埋点
    editSubject () {},
    handleDefaultChange (e) {
      if (!e) this.form.amt = 0
    }
  })
}
</script>
